import React, { useState, useEffect } from 'react'
import { 
  Row, 
  Col, 
  Card, 
  Table, 
  Button, 
  Tag, 
  Space, 
  Select, 
  Input, 
  Modal,
  Form,
  message,
  Progress,
  Avatar,
  DatePicker
} from 'antd'
import { 
  NotificationOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined,
  UserOutlined,
  SendOutlined,
  CheckCircleOutlined
} from '@ant-design/icons'
import { mockApi, UserProfile } from '@/services/mockData'
import dayjs from 'dayjs'

const { Option } = Select
const { TextArea } = Input

interface PushTask {
  id: string
  title: string
  content: string
  targetUsers: string[]
  pushType: 'immediate' | 'scheduled'
  scheduleTime?: string
  status: 'draft' | 'sending' | 'sent' | 'failed'
  sentCount: number
  totalCount: number
  createTime: string
}

const PushManagement: React.FC = () => {
  const [users, setUsers] = useState<UserProfile[]>([])
  const [pushTasks, setPushTasks] = useState<PushTask[]>([])
  const [loading, setLoading] = useState(true)
  const [modalVisible, setModalVisible] = useState(false)
  const [form] = Form.useForm()

  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = async () => {
    setLoading(true)
    try {
      const usersData = await mockApi.getUserProfiles()
      setUsers(usersData)
      
      // 模拟推送任务数据
      const tasks: PushTask[] = [
        {
          id: '1',
          title: '农业技术培训通知',
          content: '本周六上午9点将举办春季水稻种植技术培训，欢迎各位农户参加。',
          targetUsers: ['1', '2'],
          pushType: 'scheduled',
          scheduleTime: '2024-03-16 08:00',
          status: 'sent',
          sentCount: 2,
          totalCount: 2,
          createTime: '2024-03-15 10:30'
        },
        {
          id: '2',
          title: '乡村旅游活动邀请',
          content: '本周末将举办乡村旅游文化节，特色美食、民俗表演等您来体验！',
          targetUsers: ['1', '2', '3'],
          pushType: 'immediate',
          status: 'sending',
          sentCount: 1,
          totalCount: 3,
          createTime: '2024-03-15 14:20'
        },
        {
          id: '3',
          title: '农产品电商优惠',
          content: '新鲜农产品限时特惠，满100元包邮，快来选购吧！',
          targetUsers: ['1'],
          pushType: 'immediate',
          status: 'draft',
          sentCount: 0,
          totalCount: 1,
          createTime: '2024-03-15 16:45'
        }
      ]
      setPushTasks(tasks)
    } catch (error) {
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  const handleCreatePush = () => {
    form.resetFields()
    setModalVisible(true)
  }

  const handleSubmit = async (values: any) => {
    try {
      const newTask: PushTask = {
        id: Date.now().toString(),
        title: values.title,
        content: values.content,
        targetUsers: values.targetUsers,
        pushType: values.pushType,
        scheduleTime: values.scheduleTime?.format('YYYY-MM-DD HH:mm'),
        status: 'draft',
        sentCount: 0,
        totalCount: values.targetUsers.length,
        createTime: dayjs().format('YYYY-MM-DD HH:mm')
      }
      
      setPushTasks([newTask, ...pushTasks])
      setModalVisible(false)
      message.success('推送任务创建成功')
    } catch (error) {
      message.error('创建失败')
    }
  }

  const handleSend = (taskId: string) => {
    setPushTasks(tasks => 
      tasks.map(task => 
        task.id === taskId 
          ? { ...task, status: 'sending', sentCount: 1 } 
          : task
      )
    )
    message.success('开始发送推送')
  }

  const getStatusConfig = (status: PushTask['status']) => {
    const configs = {
      draft: { color: 'default', text: '草稿', icon: <EditOutlined /> },
      sending: { color: 'processing', text: '发送中', icon: <SendOutlined /> },
      sent: { color: 'success', text: '已发送', icon: <CheckCircleOutlined /> },
      failed: { color: 'error', text: '发送失败', icon: <DeleteOutlined /> }
    }
    return configs[status]
  }

  const getUserName = (userId: string) => {
    const user = users.find(u => u.id === userId)
    return user?.name || '未知用户'
  }

  const getUserRole = (userId: string) => {
    const user = users.find(u => u.id === userId)
    const roleMap = {
      farmer: '农户',
      village_admin: '村干部',
      government: '政府人员',
      enterprise: '企业代表'
    }
    return roleMap[user?.role as keyof typeof roleMap] || '未知角色'
  }

  const columns = [
    {
      title: '推送标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string) => <span style={{ fontWeight: 500 }}>{text}</span>
    },
    {
      title: '推送内容',
      dataIndex: 'content',
      key: 'content',
      render: (text: string) => (
        <span style={{ color: '#666' }}>
          {text.length > 50 ? `${text.substring(0, 50)}...` : text}
        </span>
      )
    },
    {
      title: '目标用户',
      key: 'targetUsers',
      render: (record: PushTask) => (
        <div>
          <div>共 {record.targetUsers.length} 人</div>
          <div style={{ color: '#999', fontSize: 12 }}>
            {record.targetUsers.slice(0, 2).map(userId => getUserName(userId)).join(', ')}
            {record.targetUsers.length > 2 && '...'}
          </div>
        </div>
      )
    },
    {
      title: '发送进度',
      key: 'progress',
      render: (record: PushTask) => (
        <div>
          <Progress 
            percent={Math.round((record.sentCount / record.totalCount) * 100)} 
            size="small" 
          />
          <div style={{ color: '#999', fontSize: 12 }}>
            {record.sentCount}/{record.totalCount}
          </div>
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: PushTask['status']) => {
        const config = getStatusConfig(status)
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        )
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (record: PushTask) => (
        <Space size="small">
          <Button type="link" icon={<EyeOutlined />} size="small">
            详情
          </Button>
          {record.status === 'draft' && (
            <Button 
              type="link" 
              icon={<SendOutlined />} 
              size="small"
              onClick={() => handleSend(record.id)}
            >
              发送
            </Button>
          )}
          <Button type="link" danger icon={<DeleteOutlined />} size="small">
            删除
          </Button>
        </Space>
      )
    }
  ]

  return (
    <div>
      <div className="page-title">
        <NotificationOutlined />
        精准推送
      </div>

      <Row gutter={[16, 16]}>
        {/* 用户画像统计 */}
        <Col xs={24} lg={8}>
          <Card title="用户画像统计" className="custom-card">
            <Space direction="vertical" style={{ width: '100%' }}>
              {users.map(user => (
                <Card key={user.id} size="small">
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <Avatar icon={<UserOutlined />} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 500 }}>{user.name}</div>
                      <div style={{ color: '#999', fontSize: 12 }}>
                        {getUserRole(user.id)} · {user.village}
                      </div>
                    </div>
                    <Tag color="blue">活跃</Tag>
                  </div>
                </Card>
              ))}
            </Space>
          </Card>
        </Col>

        {/* 推送任务管理 */}
        <Col xs={24} lg={16}>
          <Card 
            title="推送任务"
            extra={
              <Button type="primary" icon={<PlusOutlined />} onClick={handleCreatePush}>
                新建推送
              </Button>
            }
            className="custom-card"
          >
            <Table
              columns={columns}
              dataSource={pushTasks}
              loading={loading}
              rowKey="id"
              pagination={{
                total: pushTasks.length,
                pageSize: 10,
                showSizeChanger: true
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* 新建推送模态框 */}
      <Modal
        title="新建精准推送"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="title"
            label="推送标题"
            rules={[{ required: true, message: '请输入推送标题' }]}
          >
            <Input placeholder="请输入推送标题" />
          </Form.Item>

          <Form.Item
            name="content"
            label="推送内容"
            rules={[{ required: true, message: '请输入推送内容' }]}
          >
            <TextArea 
              rows={4} 
              placeholder="请输入推送内容" 
              maxLength={500}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="targetUsers"
            label="目标用户"
            rules={[{ required: true, message: '请选择目标用户' }]}
          >
            <Select mode="multiple" placeholder="请选择目标用户">
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  {user.name} ({getUserRole(user.id)} - {user.village})
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="pushType"
            label="推送类型"
            rules={[{ required: true, message: '请选择推送类型' }]}
          >
            <Select placeholder="请选择推送类型">
              <Option value="immediate">立即发送</Option>
              <Option value="scheduled">定时发送</Option>
            </Select>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.pushType !== currentValues.pushType}
          >
            {({ getFieldValue }) =>
              getFieldValue('pushType') === 'scheduled' ? (
                <Form.Item
                  name="scheduleTime"
                  label="发送时间"
                  rules={[{ required: true, message: '请选择发送时间' }]}
                >
                  <DatePicker
                    showTime
                    format="YYYY-MM-DD HH:mm"
                    style={{ width: '100%' }}
                    placeholder="请选择发送时间"
                  />
                </Form.Item>
              ) : null
            }
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                创建推送
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default PushManagement